<template>
  <div id="app-container">
    <!-- 查询条件开始 -->
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="字典名称" prop="dictType">
        <el-select
          v-model="queryParams.dictType"
          placeholder="字典类型"
          clearable
          size="small"
          style="width:240px"
        >
          <el-option
            v-for="type in typeOptions"
            :key="type.dictType"
            :label="type.dictName"
            :value="type.dictType"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="字典标签" prop="dictLabel">
        <el-input
          v-model="queryParams.dictLabel"
          placeholder="请输入字典数据标签"
          clearable
          size="small"
          style="width:240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="字典状态"
          clearable
          size="small"
          style="width:240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 查询条件结束 -->
    <!-- 按钮开始 -->
    <el-row :gutter="10" style="margin-bottom: 8px;">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-refresh" size="mini" @click="handleCacheAsync">缓存同步</el-button>
      </el-col>
    </el-row>
    <!-- 按钮结束 -->
    <!-- 表格开始 -->
    <el-table
      class="table_Data"
      v-loading="loading"
      border
      :data="dictDataTableList"
      @selection-change="handleSelectionChnage"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="字典编码" prop="dictCode" align="center" />
      <el-table-column label="字典标签" prop="dictLabel" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="字典键值" prop="dictValue" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="字典排序" prop="dictSort" align="center" />
      <el-table-column
        label="状态"
        prop="status"
        align="center"
        :show-overflow-tooltip="true"
        :formatter="statusFormatter"
      />
      <el-table-column label="备注" prop="remark" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" prop="createTime" align="center" width="180" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格结束 -->
    <!-- 分页开始 -->
    <el-pagination
      v-show="total>0"
      :current-page="queryParams.pageNum"
      :page-sizes="[1,5, 10, 20, 30]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 分页结束 -->
    <!-- 添加修改表单开始 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" center append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典排序" prop="dictSort">
          <el-input v-model="form.dictSort" placeholder="字典排序" clearable size="small" />
        </el-form-item>
        <el-form-item label="字典标签" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入字典标签" clearable size="small" />
        </el-form-item>
        <el-form-item label="字典键值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入字典键值" clearable size="small" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input
            v-model="defaultDictType"
            disabled
            placeholder="请输入字典类型"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              :value="dict.dictValue"
            >{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入字典备注"
            clearable
            size="small"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 添加修改表单结束 -->
  </div>
</template>

<script>
import {
  loadDictDataByType,
  loadDictDataByPage,
  insertDicData,
  modifyDicData,
  removeDicData,
  loadDictDataById,
} from "@/api/system/dict/data";
import ItemVue from "@/layout/components/Sidebar/Item.vue";
import { getDictTypeById, loadAllDic, removeDic } from "@/api/system/dict/type";
export default {
  data() {
    return {
      //字典类型下拉
      typeOptions: [],
      // 是否启用遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 分页数据总条数
      total: 0,
      // 字典表格数据
      dictDataTableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictLabel: undefined,
        status: undefined,
        dictType: undefined,
      },
      defaultDictType: undefined,
      // 表单数据
      form: {},
      // 表单校验
      rules: {
        dictLabel: [
          { required: true, message: "字典标签不能为空", trigger: "blur" },
        ],
        dictSort: [
          { required: true, message: "字典排序不能为空", trigger: "blur" },
        ],
        dictValue: [
          { required: true, message: "字典键值不能为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    getDictDataList() {
      this.loading = true;
      //查询字典
      loadDictDataByPage(
        this.addDateRange(this.queryParams, this.dateRange)
      ).then((res) => {
        this.dictDataTableList = res.data.dataList;
        this.total = res.total;
        this.loading = false;
        console.log(res.data.dataList);
      });
    },
    //监听条数发生变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getDictDataList();
    },
    //监听页数发生变化
    handleCurrentChange(val) {
      console.log("当前页数:" + val);
      this.queryParams.pageNum = val;
      this.getDictDataList();
    },
    //条件查询
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = this.total;
      this.getDictDataList();
      console.log("function handleQuery");
    },
    //重置查询条件
    resetQuery() {
      this.defaultDictType = this.queryParams.dictType;
      console.log("function resetQuery");
      this.resetForm("queryForm");
      this.dateRange = [];
      this.queryParams.dictType = this.defaultDictType;
      this.getDictDataList();
    },
    //打开添加弹出层
    handleAdd() {
      this.reset();
      this.title = "新增[" + this.queryParams.dictType + "]数据";
      this.open = true;
      console.log("function handleAdd");
    },
    //打开修改弹出层
    handleUpdate(row) {
      this.reset();
      let dictCode = row.dictCode == undefined ? this.ids[0] : row.dictCode;
      console.log("function handleUpdate");
      this.open = true;
      this.title = "数据读取中....";
      loadDictDataById(dictCode).then((res) => {
        this.form = res.data;
        this.title = "编辑[" + this.form.dictLabel + "]字典数据信息";
      });
    },
    //删除
    handleDelete(row) {
      this.loading = true;
      this.reset();
      console.log("function handleDelete");
      let dictCode = row.dictCode == undefined ? this.ids : row.dictCode;
      this.$confirm("确定要删除此记录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeDicData(dictCode).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getDictDataList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      this.loading = false;
    },
    handleCacheAsync() {
      console.log("function handleCacheAsync");
      this.loading = true;
      dictCacheAsync().then((res) => {
        this.loading = false;
        this.msgSuccess("字典数据缓存同步成功!");
      });
    },
    handleSelectionChnage(selection) {
      this.ids = selection.map((item) => item.dictCode);
      console.log(this.ids);
      this.single = false;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      console.log("function handleCacheAsync");
    },
    statusFormatter(row) {
      console.log("function statusFormatter");
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    handleSubmit() {
      //执行添加业务
      this.$refs["form"].validate((vaild) => {
        if (vaild) {
          console.log("--------------->" + this.form.dictCode);
          this.loading = true;
          if (this.form.dictCode === undefined) {
            this.form.dictType = this.defaultDictType;
            console.log("function handleSubmit");
            insertDicData(this.form)
              .then((res) => {
                this.msgSuccess("保存成功!");
                this.loading = false;
                this.getDictDataList();
                this.open = false;
              })
              .catch(() => {
                this.loading = false;
              });
            //执行修改业务
          } else {
            modifyDicData(this.form)
              .then((res) => {
                this.msgSuccess("修改成功!");
                this.loading = false;
                this.getDictDataList();
                this.open = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        }
      });
    },
    cancel() {
      this.title = "";
      this.open = false;
      console.log("function cancel");
    },
    reset() {
      this.form = {
        dictId: undefined,
        dictName: undefined,
        dictType: undefined,
        status: "0",
        remark: undefined,
      };
      this.resetForm("form");
    },
  },
  created() {
    let _that = this;
    let dictId = this.$route.params.dictId;
    //根据字典类型查询字典数据
    this.getDataByType("sys_normal_disable").then((res) => {
      this.statusOptions = res.data.dataList;
    });
    getDictTypeById(dictId).then((res) => {
      this.queryParams.dictType = res.data.dictType;
      this.defaultDictType = res.data.dictType;
      _that.getDictDataList();
    });
    //查询所有字典类型
    loadAllDic().then((res) => {
      console.log(res.data);
      this.typeOptions = res.data;
    });
  },
};
</script>

<style scoped>
#app-container {
  padding: 25px;
}
.table_Data {
  margin-top: 30px;
  margin-bottom: 25px;
}
</style>